package com.lxw.redis.study.service.impl;

import com.lxw.redis.study.dao.EmpMapper;
import com.lxw.redis.study.entity.Emp;
import com.lxw.redis.study.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmpServiceImpl implements EmpService {

    @Autowired
    EmpMapper empMapper;
    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    /**
     * 新增
     *
     * @param emp
     * @return
     */
    @Override
    public int insert(Emp emp) {
        return empMapper.insert(emp);
    }

    /**
     * 批量新增
     *
     * @param emps
     */
    @Override
    public void insertBatch(List<Emp> emps) {
        empMapper.insertBatch(emps);
    }

    /**
     * 根据主键删除
     *
     * @param id
     * @return
     */
    @Override
    public int deleteByPrimaryKey(Object id) {
        return empMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据主键批量删除
     *
     * @param
     */
    @Override
    public void deleteBatch(List<Object> ids) {
        empMapper.deleteBatch(ids);
    }

    /**
     * 根据主键更新
     *
     * @param emp
     * @return
     */
    @Override
    public int update(Emp emp) {
        return empMapper.update(emp);
    }

    /**
     * 根据主键批量更新
     *
     * @param emps
     */
    @Override
    public void updateBatch(List<Emp> emps) {
        empMapper.updateBatch(emps);
    }

    /**
     * 根据主键查找
     *缓存并发重建
     * @param id 主键
     * @return
     */
    @Override
    public Emp selectByPrimaryKey(Object id) {
        String key = "emp:" + id;
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        Object redisEmp = ops.get(key);
        if (redisEmp != null) {
            return (Emp) redisEmp;
        }
        synchronized (this) {
            redisEmp = ops.get(key);
            if (redisEmp != null) {
                return (Emp) redisEmp;
            }
            Emp emp = empMapper.selectByPrimaryKey(id);
            ops.set(key, emp);
            return emp;
        }
    }

    /**
     * 根据条件查询一条数据
     *
     * @param emp
     */
    @Override
    public Emp selectOne(Emp emp) {
        return empMapper.selectOne(emp);
    }

    /**
     * 条件查询
     *
     * @param
     * @return
     */
    @Override
    public List<Emp> selectList(Emp emp) {
        return empMapper.selectList(emp);
    }

}
